#include "LogSaver.h"

#include <qdebug.h>

LogSaver::LogSaver(QObject* parent) :QObject(parent)
{
    qfile = new QFile(logFilePath);
    qfile->open(QFile::Append);
    LogSaver1* logSaver1 = new LogSaver1();
    QThread* qThread = new QThread();
    logSaver1->moveToThread(qThread);
    connect(this, &LogSaver::signal_writeLogToFile, logSaver1, &LogSaver1::slot_writeLogToFile);
    connect(this, &QObject::destroyed, qThread, &QThread::quit);
    connect(qThread, &QThread::finished, logSaver1, &QObject::deleteLater);
    connect(qThread, &QThread::finished, qThread, &QObject::deleteLater);
    qThread->start();
}
LogSaver::~LogSaver()
{
    qfile->close();
    delete qfile;
}
void LogSaver::saveLog(QString msg, LogFlag logFlag)
{
    if (logLevel & logFlag)
    {
        QString log = QDateTime::currentDateTime().toString(QStringLiteral("yyyy.MM.dd.hh:mm:ss")) + getQStringOfLogFlag(logFlag) + msg + newLine;
        emit signal_writeLogToFile(log, qfile);
    }
}

void LogSaver::enableLogLevel(LogFlag logFlag)
{
    logLevel |= logFlag;
}

void LogSaver::disableLogLevel(LogFlag logFlag)
{
    logLevel &= (~logFlag);
}
QString LogSaver::getQStringOfLogFlag(LogFlag logFlag)
{
    switch (logFlag)
    {
    case LogSaver::Debug:
        return QString_debug;
    case LogSaver::Information:
        return QString_information;
    case LogSaver::Warning:
        return QString_warning;
    case LogSaver::Critical:
        return QString_critical;
    default:
        return "";
    }

}
int LogSaver::getLogLevel()
{
    return logLevel;
}
QString LogSaver::getLogFilePath()
{
    return logFilePath;
}

void LogSaver::setLogFilePath(QString filePath)
{
    this->logFilePath = filePath;
}


LogSaver1::LogSaver1()
{}
LogSaver1::~LogSaver1()
{
}
void LogSaver1::slot_writeLogToFile(QString msg, QFile* file)
{
    QByteArray data = msg.toLocal8Bit();
    file->write(data);
    file->flush();
}


